package com.example.onion.hxchat.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onion.hxchat.mvvm.UserViewModel;
import com.example.onion.hxchat.mvvm.WcFriendViewModel;
import com.example.onion.hxchat.room.entity.User;
import com.example.onion.hxchat.thread.PlayUserDetailThread;
import com.example.onion.hxchat.util.HttpUtils;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.myteam.R;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.FormBody;
import okhttp3.Request;

/**
 * 需要调用活动页面，需要给出用户名userName（传递到本页面的key值应该是detailUserName）
 * userName = getIntent().getStringExtra("detailUserName");
 * userId = getIntent().getStringExtra("detailUserId");
 */
public class UserDetailActivity extends AppCompatActivity {

    private Toolbar toolbar;

    private String userName;//传递过来的用户名

    private String userId;//传递过来的Id

    private String accountId;//当前登录的用户的id

    private ImageView userImgTv;//显示用户头像的部件

    private TextView userSexTv;//显示用户性别的文本部件

    private TextView userGradeTv;//显示用户年级的文本部件

    private TextView userNameTv;//显示用户昵称的文本部件

    private TextView userLabelTv;//显示用户标签的文本部件

    private TextView userSpyTv;//显示用户专业的文本部件

    private TextView userAgeTv;//显示用户年龄的文本部件

    private TextView userEmailTv;//显示用户邮箱的文本部件

    private TextView userAbilityTv;//显示用户能力文本部件
    private UserViewModel userViewModel;

//    class MyHandler extends Handler {
//        public MyHandler() {
//
//        }
//
//        public MyHandler(Looper looper) {
//            super(looper);
//        }
//
//        @Override
//        public void handleMessage(Message msg) {
//            if (msg.what == PlayUserDetailThread.IS_FINISH) {
//                User data = (User) msg.obj;
//                setContent(data);
//            }else if (msg.what == PlayUserDetailThread.IS_FAILED){
//                Toast.makeText(UserDetailActivity.this,"网络获取数据失败",Toast.LENGTH_LONG);
//            }
//
//        }
//    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PlayUserDetailThread.DETAIL_IS_FINISH:
                    User data = (User) msg.obj;
                    setContent(data);
                    break;
                case PlayUserDetailThread.DETAIL_IS_FAILED:
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_detail);
        initUserId();
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
//        String url = "http://49.232.60.155:8080/AppServer_war/GetUserInfoByIdServlet";
//        new GetUserInfoAsyncTask().execute(url, "second params");
        new Thread(new PlayUserDetailThread(userId,handler)).start();
        initView();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    private void initUserId() {
        //传递给查看用户详细界页面的用户名称（最好根据需要传递到的不同的页面，命名kEY，此处需要传递到查看用户详细界面，加前缀detail+UserName）
        userName = getIntent().getStringExtra("detailUserName");
        userId = getIntent().getStringExtra("detailUserId");
        accountId = PassWordHelp.readPassword(UserDetailActivity.this)[0];
    }

    private void initView() {
        userNameTv = findViewById(R.id.user_detail_username);
        userImgTv = findViewById(R.id.user_detail_userimg);
        userSexTv = findViewById(R.id.user_detail_usersex);
        userGradeTv = findViewById(R.id.user_detail_userYear);
        userLabelTv = findViewById(R.id.user_detail_userlabel);
        userSpyTv = findViewById(R.id.user_detail_userSpy);
        userAgeTv = findViewById(R.id.user_detail_userAge);
        userEmailTv = findViewById(R.id.user_detail_userEmail);
        userAbilityTv = findViewById(R.id.user_detail_userAbility);
        toolbar = findViewById(R.id.user_detail_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }


    @SuppressLint("SetTextI18n")
    private void setContent(User user) {
        Log.e("userDetailActivity", user.toString());
        userNameTv.setText(user.getUserName());
        userSexTv.setText(user.getUserSex());

        userGradeTv.setText(user.getUserGrade());

        userLabelTv.setText(user.getUserLabel1() + "***" + user.getUserLabel2() + "***" + user.getUserLabel3() + "***" + user.getUserLabel4());

        userSpyTv.setText(user.getUserSpy());
        userAgeTv.setText(String.valueOf(user.getUserAge()));
        userEmailTv.setText(user.getUserEmail());
        userAbilityTv.setText(String.valueOf(user.getUserAbility()));
    }

    @SuppressLint("StaticFieldLeak")
    class GetUserInfoAsyncTask extends AsyncTask<String, Void, User> {

        User muser;
        boolean isSuccess = false;

        @Override
        protected User doInBackground(String... strings) {
            HttpUtils httpUtils = HttpUtils.getInstance();
            String url = strings[0];
            String secondParam = strings[1];
            Log.e("AsyncTask Second Params", secondParam);
            Log.e("AsyncTask Url Params", url);
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("userId", userId);
            FormBody formBody = builder.build();
            httpUtils.asyncPost(url, formBody, new HttpUtils.HttpCallBack() {
                @Override
                public void onError(Request request, IOException e) {

                }

                @Override
                public void onSuccess(Request request, String result) {
                    Gson gson = new Gson();
                    User users = gson.fromJson(result, (Type) User.class);
                    UserViewModel userViewModel = new ViewModelProvider(UserDetailActivity.this).get(UserViewModel.class);
                    userViewModel.insertUser(users);
                    muser = users;
                    Log.e("diBackground user", muser.toString());
                    isSuccess = true;
                }
            });
            while (!isSuccess) {

            }
            return muser;
        }

        @Override
        protected void onPostExecute(User user) {
            super.onPostExecute(user);
            Log.e("onPostExecute user", user.toString());
            userViewModel.insertUser(user);
            setContent(user);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_user_detail_menu, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        Intent intent = null;
        switch (item.getItemId()) {
            case android.R.id.home://系统自带的返回箭头的资源id
                finish();
                break;
            case R.id.user_detail_chat_menu_item://查看详细信息界面的菜单项（发送信息）
                intent = new Intent(UserDetailActivity.this, MsgTestActivity.class);
                //传递给查看用户详细界页面的用户名称（最好根据需要传递到的不同的页面，命名kEY，
                // 此处需要传递到聊天界面，加前缀chat+UserName）
                intent.putExtra("chatUserName", userName);
                intent.putExtra("chatUserId", userId);
                startActivity(intent);
                Toast.makeText(UserDetailActivity.this, "发送信息", Toast.LENGTH_SHORT).show();
                break;
            case R.id.user_detail_apply_friend_menu_item://查看详细信息界面的菜单项（添加好友）
                intent = new Intent(UserDetailActivity.this, ApplyFriendActivity.class);
                //传递给查看用户详细界页面的用户名称（最好根据需要传递到的不同的页面，命名kEY，
                // 此处需要传递到添加好友界面，加前缀apply+UserName）
                intent.putExtra("applyUserName", userName);
                intent.putExtra("applyUserId", userId);
                startActivity(intent);
                Toast.makeText(UserDetailActivity.this, "添加好友", Toast.LENGTH_SHORT).show();
                break;
            case R.id.user_detail_delete_friend_menu_item://查看详细信息界面的菜单项（删除好友）
                intent = new Intent(UserDetailActivity.this, ScanUserActivity.class);
                WcFriendViewModel friendViewModel = new ViewModelProvider(this).get(WcFriendViewModel.class);
                friendViewModel.deltetFreind(accountId, userId);
                //环信后台删除好友
                try {
                    EMClient.getInstance().contactManager().deleteContact(userId);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Log.e("UserDetailActivity", "环信删除好友异常" + e.getDescription());
                }
                //传递给查看用户详细界页面的用户名称（最好根据需要传递到的不同的页面，命名kEY，
                // 此处需要传递到添加好友界面，加前缀apply+UserName）
                intent.putExtra("scanUserName", userName);
                intent.putExtra("scanUserId", userId);
                startActivity(intent);
                Toast.makeText(UserDetailActivity.this, "删除好友", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


}
